package com.qiaofang.applet.rest;

import com.alibaba.fastjson.JSONObject;
import com.qiaofang.applet.common.constant.V10Constants;
import com.qiaofang.applet.common.context.QfContext;
import com.qiaofang.applet.common.context.QfContextHolder;
import com.qiaofang.applet.common.dto.DataRequest;
import com.qiaofang.applet.common.dto.DataResponse;
import com.qiaofang.applet.common.dto.PageDataRequest;
import com.qiaofang.applet.common.util.PageUtil;
import com.qiaofang.applet.service.other.domain.Corporation;
import com.qiaofang.applet.service.other.service.CityCompanyService;
import com.qiaofang.applet.service.other.service.CorporationService;
import com.qiaofang.applet.service.other.service.dto.*;
import com.qiaofang.applet.service.property.service.PropertyEntrustService;
import com.qiaofang.applet.service.property.service.dto.UniqueUuidDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: youqing.yang
 * @create: 2020/09/24 17:49
 **/
@Slf4j
@RestController
@RequestMapping("/api/web/propertyEntrust")
@Api(tags = "委托：房源委托")
public class PropertyEntrustController {
    private static RestTemplate restTemplate = new RestTemplate();

    @Value("${V10.api.url}")
    private String domain;

    @Autowired
    private CorporationService corporationService;

    @Autowired
    private CityCompanyService cityCompanyService;

    @Autowired
    private PropertyEntrustService propertyEntrustService;

    @RequestMapping(value = "getEstateByKeyword", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "模糊查询小区", notes = "模糊查询小区")
    public DataResponse getEstateByKeyword(@RequestBody @Valid DataRequest<EstateFuzzyQueryDto> request) {
        DataResponse dataResponse = new DataResponse();
        try {
            QfContext context = QfContextHolder.getContext();
            Corporation corporation = corporationService.getCorporationByCorporationCode(context.getCorporationCode());
            if (corporation == null) {
                dataResponse.setStatus(2);
                dataResponse.setMessage("获取集团信息失败");
                return dataResponse;
            } else if (StringUtils.isBlank(corporation.getV10Url())) {
                dataResponse.setStatus(2);
                dataResponse.setMessage("集团配置信息v10Url为空");
                return dataResponse;
            }
            String companyUuid = cityCompanyService.getCompanyUuid(context.getCityCode(), context.getCorporationCode());
            HttpHeaders requestHeaders = new HttpHeaders();
            requestHeaders.add("Content-Type", "multipart/form-data;charset=utf-8");
            String url = corporation.getV10Url() + V10Constants.SEARCH_ESTATE_KERWORD;
            MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
            params.add("companyUuid", companyUuid);
            params.add("params", request.getParam().getEstateName());
            HttpEntity<MultiValueMap<String,Object>> requestEntity = new HttpEntity<>(params, requestHeaders);
            JSONObject result = restTemplate.postForEntity(url, requestEntity, JSONObject.class).getBody();

            log.info("send getEstateByKeyword response:{}", result);
            if (StringUtils.equals(result.get("status").toString(),"1")){
                dataResponse.setStatus(1);
                dataResponse.setMessage("成功");
            }else {
                dataResponse.setStatus(2);
                dataResponse.setMessage("失败");
            }
            dataResponse.setT(result);
        } catch (RestClientException e) {
            log.error("getEstateByKeyword error:{}",e);
            dataResponse.setMessage("获取失败");
        }
        return dataResponse;
    }

    @RequestMapping(value = "getEstatePersonLiable", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "获取楼盘责任人", notes = "获取楼盘责任人")
    public DataResponse getEstatePersonLiable(@RequestBody @Valid DataRequest<EstateFuzzyQueryDto> request) {
        DataResponse dataResponse = new DataResponse();
        try {
            QfContext context = QfContextHolder.getContext();
            Corporation corporation = corporationService.getCorporationByCorporationCode(context.getCorporationCode());
            if (corporation == null) {
                dataResponse.setStatus(2);
                dataResponse.setMessage("获取集团信息失败");
                return dataResponse;
            } else if (StringUtils.isBlank(corporation.getV10Url())) {
                dataResponse.setStatus(2);
                dataResponse.setMessage("集团配置信息v10Url为空");
                return dataResponse;
            }
            String companyUuid = cityCompanyService.getCompanyUuid(context.getCityCode(), context.getCorporationCode());
            HttpHeaders requestHeaders = new HttpHeaders();
            requestHeaders.add("Content-Type", "multipart/form-data;charset=utf-8");
            String url = corporation.getV10Url() + V10Constants.GET_ESTATE_PERSON_LIABLE;
            MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
            params.add("companyUuid", companyUuid);
            params.add("params", request.getParam().getEstateName());
            HttpEntity<MultiValueMap<String,Object>> requestEntity = new HttpEntity<>(params, requestHeaders);
            JSONObject result = restTemplate.postForEntity(url, requestEntity, JSONObject.class).getBody();
            log.info("send getEstatePersonLiable response:{}", result);
            if (StringUtils.equals(result.get("status").toString(),"1")){
                dataResponse.setStatus(1);
                dataResponse.setMessage("成功");
            }else {
                dataResponse.setStatus(2);
                dataResponse.setMessage("失败");
            }
            dataResponse.setT(result);
        } catch (RestClientException e) {
            log.error("getEstatePersonLiable error:{}", e);
            dataResponse.setMessage("获取失败");
        }
        return dataResponse;
    }

    @RequestMapping(value = "savePropertyEntrust", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "新增房源委托", notes = "新增委托")
    public DataResponse savePropertyEntrust(@RequestBody @Valid DataRequest<PropertyEntrustQueryDto> request) {
        DataResponse dataResponse = new DataResponse();
        try {
            QfContext context = QfContextHolder.getContext();
            Corporation corporation = corporationService.getCorporationByCorporationCode(context.getCorporationCode());
            if (corporation == null) {
                dataResponse.setStatus(2);
                dataResponse.setMessage("获取集团信息失败");
                return dataResponse;
            } else if (StringUtils.isBlank(corporation.getV10Url())) {
                dataResponse.setStatus(2);
                dataResponse.setMessage("集团配置信息v10Url为空");
                return dataResponse;
            }
            String companyUuid = cityCompanyService.getCompanyUuidByMainCity(context.getCorporationCode(), context.getCityCode());
            HttpHeaders requestHeaders = new HttpHeaders();
            requestHeaders.add("Content-Type", "multipart/form-data;charset=utf-8");
            PropertyEntrustQueryDto param = request.getParam();
            param.setCompanyUuid(companyUuid);
            //将javabean转为Map
            Map<String, Object> params = beanToMap(param);
            MultiValueMap<String, Object> paramsReq = new LinkedMultiValueMap<>();
            paramsReq.setAll(params);
            String url = corporation.getV10Url() + V10Constants.SAVE_PROPERTRY_ENTRUST;
            HttpEntity<MultiValueMap<String,Object>> requestEntity = new HttpEntity<>(paramsReq, requestHeaders);
            JSONObject result = restTemplate.postForEntity(url, requestEntity, JSONObject.class).getBody();
            if (StringUtils.equals(result.get("status").toString(),"1")){
                dataResponse.setStatus(1);
                dataResponse.setMessage("成功");
            }else {
                dataResponse.setStatus(2);
                dataResponse.setMessage("失败");
            }
            log.info("send savePropertyEntrust response:{}", result);
            dataResponse.setT(result);
        } catch (RestClientException e) {
            log.error("savePropertyEntrust error:{}", e);
            dataResponse.setMessage("新增失败");
        }
        return dataResponse;
    }

    @RequestMapping(value = "getPropertyEntrustPage", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "获取房源委托列表", notes = "分页获取房源委托")
    public DataResponse getPropertyEntrustPage(@RequestBody @Valid DataRequest<PropertyEntrustQueryDto> request) {
        DataResponse dataResponse = new DataResponse();
        try {
            QfContext context = QfContextHolder.getContext();
            Corporation corporation = corporationService.getCorporationByCorporationCode(context.getCorporationCode());
            if (corporation == null) {
                dataResponse.setStatus(2);
                dataResponse.setMessage("获取集团信息失败");
                return dataResponse;
            } else if (StringUtils.isBlank(corporation.getV10Url())) {
                dataResponse.setStatus(2);
                dataResponse.setMessage("集团配置信息v10Url为空");
                return dataResponse;
            }
            String companyUuid = cityCompanyService.getCompanyUuid(context.getCityCode(), context.getCorporationCode());
            HttpHeaders requestHeaders = new HttpHeaders();
            requestHeaders.add("Content-Type", "multipart/form-data;charset=utf-8");
            PropertyEntrustQueryDto param = request.getParam();
            param.setCompanyUuid(companyUuid);
            //将javabean转为Map
            Map<String, Object> params = beanToMap(param);
            MultiValueMap<String, Object> paramsReq = new LinkedMultiValueMap<>();
            paramsReq.setAll(params);
            String url = corporation.getV10Url() + V10Constants.GET_PROPERTY_ENTRUST_PAGE;
            HttpEntity<MultiValueMap<String,Object>> requestEntity = new HttpEntity<>(paramsReq, requestHeaders);
            JSONObject result = restTemplate.postForEntity(url, requestEntity, JSONObject.class).getBody();
            if (StringUtils.equals(result.get("status").toString(),"1")){
                dataResponse.setStatus(1);
                dataResponse.setMessage("成功");
            }else {
                dataResponse.setStatus(2);
                dataResponse.setMessage("失败");
            }
            log.info("send getPropertyEntrustPage response:{}", result);
            dataResponse.setT(result);
        } catch (RestClientException e) {
            log.error("getPropertyEntrustPage error:{}", e);
            dataResponse.setMessage("获取失败");
        }
        return dataResponse;

    }

    @RequestMapping(value = "getEmployeeEntrusts", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "获取经纪人委托列表", notes = "获取经纪人委托列表")
    public DataResponse<Page<PropertyEntrustDto>> getEmployeeEntrusts(@RequestBody @Valid PageDataRequest<EmployeeEntrustQueryDto> request) {
        return DataResponse.ok(propertyEntrustService.getEmployeeEntrusts(request.getParam(), PageUtil.getPageable(request)));
    }

    @RequestMapping(value = "acceptEntrustMyself", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "我受理（经纪人操作）", notes = "我受理（经纪人操作）")
    public DataResponse<Object> acceptEntrustMyself(@RequestBody @Valid DataRequest<PropertyEntrustIdDto> request) {
        propertyEntrustService.acceptEntrustMyself(request.getParam().getPropertyEntrustId());
        return DataResponse.ok();
    }

    /**
     * 将对象转换为map
     *
     * @param bean
     * @return
     */
    public static <T> Map<String, Object> beanToMap(T bean) {
        Map<String, Object> map = new HashMap<String, Object>();
        ;
        if (bean != null) {
            BeanMap beanMap = BeanMap.create(bean);
            for (Object key : beanMap.keySet()) {
                if (beanMap.get(key) == null) {
                    continue;
                }
                map.put(key.toString(), beanMap.get(key));
            }
        }
        return map;
    }
}
